package com.example.nettydemo.NIO.组件.NIOSelector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
//java.io.IOException: 远程主机强迫关闭了一个现有的连接。
public class 服务端 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();//创建 Selector选择器
        //绑定一个端口7777
        serverSocketChannel.socket().bind(new InetSocketAddress(7777));
        serverSocketChannel.configureBlocking(false);//设置为非阻塞
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if(selector.select(1000) == 0) {//没事情发生
                System.out.println("服务器等待1秒，无连接");
                continue;
            }
//            selector.keys();//获取所有的Selection
            Set<SelectionKey> keys = selector.selectedKeys();//获取所有响应的Selection

            Iterator<SelectionKey> iterator = keys.iterator();

            while (iterator.hasNext()){//遍历所有SelectionKey
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {//如果是OP_ACCEPT状态  说明连接了
                    SocketChannel socketChannel = serverSocketChannel.accept();//获取通道
                    System.out.println("SocketChannel的哈希"+socketChannel.hashCode());
                    socketChannel.configureBlocking(false);//设置为非阻塞的
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(10246));
                }
                if(key.isReadable()) {//发生了OP_READ
                    //通过 key  f反向获取Channel通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = (ByteBuffer)key.attachment();//获取ByteBuffer
                    System.out.println(byteBuffer.limit());
                    channel.read(byteBuffer);
                    System.out.println("客户端:"+ new String(byteBuffer.array()));
                }
                iterator.remove();//删除  当前这个 已经唤醒的Channel

            }
        }


    }
}
